package com.biz.user.websocket;

import com.biz.websocket.config.*;
import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;

import javax.websocket.*;
import javax.websocket.server.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

/**
 * @Description
 *  websocket 业务使用
 * @Author liuxi
 * @Date 2024/4/23
 **/
@Slf4j
@Component
@ServerEndpoint(value = "/demo/socket", configurator = WebSocketServerConfig.class)
public class LxyDemoWebSocket {

    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在线客户端
     */
    private static Map<String, LxyDemoWebSocket> clients = new ConcurrentHashMap<>();

    /**
     * 某个客户端连接的会话
     */
    private Session session;

    /**
     * 标识当前绘画的KEY
     */
    private String erp = "";

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        try {
            Map<String, Object> userProperties = config.getUserProperties();
            String erp = (String) userProperties.get("erp");
            this.erp = erp;
            this.session = session;
            if (clients.containsKey(this.erp)) {
                clients.get(this.erp).session.close();
                clients.remove(this.erp);
                onlineCount.decrementAndGet();
            }
            clients.put(this.erp, this);
            onlineCount.incrementAndGet();
            log.info("有新连接加入:{},当前在线人数：{}", erp, onlineCount.get());
            sendMessage("连接成功", session);
        } catch (IOException e) {
            log.error("建立链接错误{}", e.getMessage(), e);
        }
    }

    @OnClose
    public void onClose() {
        try {
            if (clients.containsKey(erp)) {
                clients.get(erp).session.close();
                clients.remove(erp);
                onlineCount.decrementAndGet();
            }
            log.info("有一连接关闭：{}，当前在线人数为：{}", this.erp, onlineCount.get());
        } catch (Exception e) {
            log.error("连接关闭错误，错误原因{}", e.getMessage(), e);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", this.erp, message);
        //心跳机制
        if (message.equals("ping")) {
            this.sendMessage("pong", session);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Socket:{},发生错误,错误原因{}", erp, error.getMessage(), error);
        try {
            session.close();
        } catch (IOException e) {
            log.error("onError.Exception{}", e.getMessage(), e);
        }
    }

    /**
     * 指定发送消息
     */
    public void sendMessage(String message, Session session) {
        log.info("服务端给客户端[{}]发送消息{}", this.erp, message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("{}发送消息发生异常，异常原因{}", this.erp, message);
        }
    }

    /**
     * 群发消息
     */
    public void sendMessage(String message) {
        for (Map.Entry<String, LxyDemoWebSocket> sessionEntry : clients.entrySet()) {
            String erp = sessionEntry.getKey();
            LxyDemoWebSocket socket = sessionEntry.getValue();
            Session session = socket.session;
            log.info("服务端给客户端[{}]发送消息{}", erp, message);
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("{}发送消息发生异常，异常原因{}", this.erp, message);
            }
        }
    }

}
